-
Notifications
You must be signed in to change notification settings - Fork 5.3k
New Components - tuya #16474
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
New Components - tuya #16474
Conversation
The latest updates on your projects. Learn more about Vercel for Git ↗︎ 3 Skipped Deployments
|
WalkthroughThis update introduces a comprehensive Tuya integration, adding actions for listing homes and devices, sending device instructions, and a polling-based trigger for device parameter changes. The Tuya app is fully implemented with dynamic option loading and API methods. Supporting files include test data and updated dependencies. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Action
participant TuyaApp
participant TuyaAPI
User->>Action: Trigger action (e.g., List Devices)
Action->>TuyaApp: Call method (e.g., listUserDevices or listHomeDevices)
TuyaApp->>TuyaAPI: Make API request with credentials
TuyaAPI-->>TuyaApp: Return device/home data
TuyaApp-->>Action: Return data
Action-->>User: Output result and summary
sequenceDiagram
participant Source
participant TuyaApp
participant TuyaAPI
participant EventDB
Source->>TuyaApp: List devices (by home or user)
TuyaApp->>TuyaAPI: API call for device list
TuyaAPI-->>TuyaApp: Return device list
TuyaApp-->>Source: Device list
loop For each device
Source->>TuyaApp: Get device status
TuyaApp->>TuyaAPI: API call for device status
TuyaAPI-->>TuyaApp: Return status
TuyaApp-->>Source: Status data
Source->>EventDB: Compare with cached parameter
alt Changed
Source->>EventDB: Update cache
Source-->>User: Emit event
end
end
Assessment against linked issues
Poem
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 ESLint
components/tuya/sources/new-device-parameter-updated/test-event.mjsOops! Something went wrong! :( ESLint: 8.57.1 Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'jsonc-eslint-parser' imported from /eslint.config.mjs components/tuya/tuya.app.mjsOops! Something went wrong! :( ESLint: 8.57.1 Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'jsonc-eslint-parser' imported from /eslint.config.mjs components/tuya/sources/new-device-parameter-updated/new-device-parameter-updated.mjsOops! Something went wrong! :( ESLint: 8.57.1 Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'jsonc-eslint-parser' imported from /eslint.config.mjs ✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 7
🧹 Nitpick comments (3)
components/tuya/actions/list-devices/list-devices.mjs (2)
4-8
: Update description to reflect dual functionality.The description only mentions listing devices associated with a home, but the action actually supports listing devices for both a home and a user.
- description: "Get a list of devices associated with a home. [See the documentation](https://developer.tuya.com/en/docs/cloud/d7ee73aadb?id=Kawfjer0wkt2a)", + description: "Get a list of devices associated with a home or user. [See the documentation](https://developer.tuya.com/en/docs/cloud/d7ee73aadb?id=Kawfjer0wkt2a)",
36-40
: Improve handling of empty results.The code only sets a summary when devices are found, but should also provide feedback when no devices are found.
if (response?.result?.length) { $.export("$summary", `Found ${response.result.length} device${response.result.length === 1 ? "" : "s"}`); + } else { + $.export("$summary", "No devices found"); }components/tuya/tuya.app.mjs (1)
90-94
: Passdata
only for non-GET requestsSome HTTP clients treat a body on
GET
as invalid.
A quick guard avoids surprises:const response = await this._getClient().request({ method, path, - body: data, + ...(method === "GET" ? {} : { body: data }), });
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
pnpm-lock.yaml
is excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (6)
components/tuya/actions/list-devices/list-devices.mjs
(1 hunks)components/tuya/actions/list-homes/list-homes.mjs
(1 hunks)components/tuya/actions/send-instructions-to-device/send-instructions-to-device.mjs
(1 hunks)components/tuya/package.json
(2 hunks)components/tuya/sources/new-device-activated/new-device-activated.mjs
(1 hunks)components/tuya/tuya.app.mjs
(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
- GitHub Check: pnpm publish
- GitHub Check: Verify TypeScript components
- GitHub Check: Lint Code Base
- GitHub Check: Publish TypeScript components
🔇 Additional comments (7)
components/tuya/package.json (2)
3-3
: Version increment looks appropriate.The version update from 0.0.1 to 0.1.0 follows semantic versioning principles, correctly indicating significant new functionality being added to the package.
15-18
:✅ Verification successful
Dependencies section looks good, but verify Tuya connector version.
The dependencies are properly structured with appropriate version ranges. Make sure that "@tuya/tuya-connector-nodejs" v2.1.2 is the latest stable version to ensure access to all necessary API features and security fixes.
🏁 Script executed:
#!/bin/bash # Check if there are newer versions of the Tuya connector package npm view @tuya/tuya-connector-nodejs versions --json | jq 'if type=="array" then .[-5:] else . end' # Check for any security advisories npm audit @tuya/tuya-connector-nodejs || echo "No direct vulnerability info available"Length of output: 2468
Confirmed Tuya connector version is up to date
Verified that
@tuya/[email protected]
is the latest stable release and there are no direct vulnerabilities reported against it. The dependencies section is good to merge.components/tuya/actions/send-instructions-to-device/send-instructions-to-device.mjs (1)
3-69
: Well-structured action component with good organization.The component properly implements the Pipedream action architecture with appropriate props, dynamic loading, and API interaction.
components/tuya/sources/new-device-activated/new-device-activated.mjs (2)
4-43
: Well-implemented polling source with proper deduplication and state management.The component correctly implements a polling-based source with dedupe settings, database persistence, and appropriate prop definitions.
38-50
:✅ Verification successful
Verify timestamp format and comparison.
The code assumes
device.active_time
and the storedlastTs
use the same format and are directly comparable. If these are in different formats or time zones, it could cause issues with event detection.Verify that the timestamps are in the same format and are correctly comparable:
🏁 Script executed:
#!/bin/bash # Find and display examples of the active_time format from the Tuya API documentation echo "Searching for active_time in Tuya API docs..." rg -A 2 -B 2 "active_time" --jsonLength of output: 4335
🏁 Script executed:
#!/bin/bash # Display the beginning of the source file to inspect how `devices` and `active_time` are obtained sed -n '1,120p' components/tuya/sources/new-device-activated/new-device-activated.mjsLength of output: 1913
Active_time is a numeric epoch timestamp and directly comparable
I’ve confirmed that
device.active_time
is returned by the Tuya Cloud API as a UNIX‐epoch number (seconds since 1970), andlastTs
is stored and retrieved as the same numeric value viathis.db
. The direct>=
andMath.max
comparisons are therefore safe—no format or timezone conversions are needed.components/tuya/tuya.app.mjs (1)
78-84
: Consider memoising the Tuya client
_getClient()
instantiates a newTuyaContext
on every request.
If the SDK performs auth handshakes or creates sockets, this can be wasteful.
Storing a single instance (e.g. inthis._client
) would cut overhead.[ suggest_optional_refactor ]
components/tuya/actions/list-homes/list-homes.mjs (1)
18-27
: Action depends on fixed helpers — verify once_makeRequest
is returnedWith the bug in
_makeRequest
corrected, ensure this action still handles
cases whereresponse.result
isundefined
(e.g. no homes found).-const response = await this.tuya.listHomes({ userId: this.userId }); -if (response?.result?.length) { - $.export("$summary", `Found ${response.result.length} home${response.result.length === 1 ? "" : "s"}`); -} -return response; +const response = await this.tuya.listHomes({ userId: this.userId }); +const homes = response?.result ?? []; +$.export("$summary", `Found ${homes.length} home${homes.length === 1 ? "" : "s"}`); +return response;This keeps the summary logic robust even when the API legitimately returns an empty array.
components/tuya/actions/send-instructions-to-device/send-instructions-to-device.mjs
Show resolved
Hide resolved
components/tuya/actions/send-instructions-to-device/send-instructions-to-device.mjs
Show resolved
Hide resolved
components/tuya/sources/new-device-activated/new-device-activated.mjs
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
♻️ Duplicate comments (3)
components/tuya/tuya.app.mjs (3)
85-99
:⚠️ Potential issue
_makeRequest()
still returnsundefined
on the happy-pathThis was flagged in the previous review but hasn’t been addressed.
Because the function neverreturn
s a value when the request is successful, every wrapper (listHomes
,listUserDevices
, …) resolves toundefined
, breaking dynamic props and any consumer relying on the data.if (!response.success) { console.log(response); throw new ConfigurationError(`${response.msg}`); } + // Return the full response (or `response.result` if callers only need the + // payload) so that helpers receive actual data + return response;
12-19
:⚠️ Potential issueUnsafe nested-destructuring can crash option loading
If
listUsers()
fails or returns an unexpected payload,
const { result: { list } } = …
throws aTypeError
, preventing the UI from loading the prop options.-const { result: { list } } = await this.listUsers(); -return list?.map(({ user_id: value, user_name: label }) => ({ label, value })) || []; +const { result } = await this.listUsers(); +const list = result?.list ?? []; +return list.map(({ user_id: value, user_name: label }) => ({ label, value }));
123-130
: 🛠️ Refactor suggestion
sendInstructionsToDevice()
still accepts arbitrarydata
, no validationThe Tuya API expects a JSON body
{ "commands": [...] }
.
Allowing any payload without validation can lead to silent no-ops or malformed requests.
Please validate the input and make the signature clearer.-sendInstructionsToDevice({ - deviceId, data, -}) { - return this._makeRequest({ - method: "POST", - path: `/v1.0/devices/${deviceId}/commands`, - data, - }); +sendInstructionsToDevice({ deviceId, commands }) { + if (!Array.isArray(commands) || !commands.length) { + throw new ConfigurationError("`commands` must be a non-empty array"); + } + return this._makeRequest({ + method: "POST", + path: `/v1.0/devices/${deviceId}/commands`, + data: { commands }, + }); }
🧹 Nitpick comments (1)
components/tuya/tuya.app.mjs (1)
78-84
: Consider caching the Tuya client instance
_getClient()
instantiatesTuyaContext
on every call, adding unnecessary overhead and preventing connection pooling.
Storing the client inthis
after first creation is a low-effort optimisation.-_getClient() { - return new TuyaContext({ - baseUrl: this.$auth.base_url, - accessKey: this.$auth.client_id, - secretKey: this.$auth.client_secret, - }); +_getClient() { + if (!this._client) { + this._client = new TuyaContext({ + baseUrl: this.$auth.base_url, + accessKey: this.$auth.client_id, + secretKey: this.$auth.client_secret, + }); + } + return this._client; }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
components/tuya/tuya.app.mjs
(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
- GitHub Check: pnpm publish
- GitHub Check: Verify TypeScript components
- GitHub Check: Publish TypeScript components
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
🧹 Nitpick comments (1)
components/tuya/sources/new-device-parameter-updated/new-device-parameter-updated.mjs (1)
50-54
: Add defensive checks for device status structure.The method should handle cases where the device object might not have the expected structure.
getCurrentValue(device) { + if (!device?.status || !Array.isArray(device.status)) { + return undefined; + } const { status } = device; const relevantStatus = status.find(({ code }) => code === this.deviceParameter); return relevantStatus?.value; },
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
components/tuya/sources/new-device-parameter-updated/new-device-parameter-updated.mjs
(1 hunks)components/tuya/sources/new-device-parameter-updated/test-event.mjs
(1 hunks)components/tuya/tuya.app.mjs
(1 hunks)
✅ Files skipped from review due to trivial changes (1)
- components/tuya/sources/new-device-parameter-updated/test-event.mjs
⏰ Context from checks skipped due to timeout of 90000ms (4)
- GitHub Check: Publish TypeScript components
- GitHub Check: pnpm publish
- GitHub Check: Verify TypeScript components
- GitHub Check: Lint Code Base
🔇 Additional comments (2)
components/tuya/tuya.app.mjs (2)
76-91
: Good fix for the return statement!The
_makeRequest
method now correctly returns the response object, which resolves the previous issue where all helper methods would resolve toundefined
.
112-120
: Good fix for the command payload!The
sendInstructionsToDevice
method now correctly accepts and passes thedata
parameter containing the commands to the API, addressing the previous issue where commands were ignored.
components/tuya/sources/new-device-parameter-updated/new-device-parameter-updated.mjs
Show resolved
Hide resolved
components/tuya/sources/new-device-parameter-updated/new-device-parameter-updated.mjs
Show resolved
Hide resolved
@vunguyenhung I think there may be multilple ways to create user IDs. The IDs Sergio and I were able to create can be seen in the UI here: Cloud -> Project Management -> Open Project -> Devices -> Link App Account. ![]() |
/approve |
Resolves #9874
Summary by CodeRabbit